package service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import dao.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import pojo.Book;
import pojo.User;
import pojo.User2;
import until.SqlSessionFactoryUtils;

import java.util.List;

public class UserLoginService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
    public int searchUser(String username,String password){
        SqlSession sqlSession = factory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.select(username, password);
        if (ObjectUtil.isNotEmpty(user)){
            return 1;
        }
        return 0;
    }
    public User searchUser2(String username,String password){
        SqlSession sqlSession = factory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.select(username, password);
    }
    public User searchUserId(String username){
        SqlSession sqlSession = factory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUserId(username);
    }
    public int updateUser(String username,String password,String phone,String email,String address ){
        SqlSession sqlSession = factory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int result = mapper.updateUser(username, password, phone, email, address);
        sqlSession.commit(); // 提交事务
        sqlSession.close(); // 关闭会话
        return result;
    }
    public List<User2> searchUserList(){
        SqlSession sqlSession = factory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.searchUserList();
    }
    public int updateUserAdmin(String id,String username,String password,String phone,String email,String address,String isAdmin ){
        SqlSession sqlSession = factory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int i =  mapper.updateUserAdmin(id, username, password, phone, email, address, isAdmin);
        sqlSession.commit();
        return i;
    }
    public int deleteUserAdmin(long id){
        SqlSession sqlSession = factory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int i =  mapper.deleteUserAdmin(id);
        sqlSession.commit();
        return i;
    }
}
